package leetcode;

/**
 * Created by Ghost on 2014/11/22.
 */
public class Flatten_Binary_Tree_to_Linked_List {
    public void flatten(TreeNode root) {

        if(root!=null){
            flatten(root.left);
            flatten(root.right);
            TreeNode tmpR = root.right;
            root.right = root.left;
            root.left = null;
            TreeNode cur = root.right;
            if(cur==null){
                root.right = tmpR;
            }
            else{
                while(cur.right!=null){
                    cur = cur.right;
                }
                cur.right = tmpR;
            }
        }
    }
    public static void main(String[] args){
        Flatten_Binary_Tree_to_Linked_List flatten_binary_tree_to_linked_list = new Flatten_Binary_Tree_to_Linked_List();
        TreeNode root = new TreeNode(1);
//        root.right = new TreeNode(2);
//        root.right.right = new TreeNode(4);
//        root.right.right.right = new TreeNode(5);
//        root.right.right.right.right = new TreeNode(6);

        flatten_binary_tree_to_linked_list.flatten(root);
        while(root!=null){
            System.out.print(root.val);
            root = root.right;
        }
    }
}
